import 'dart:io';

import 'package:flutter/material.dart';
import 'package:netstorage/pages/flutter2js_by_runjs.dart';
import 'package:path_provider/path_provider.dart';
import 'package:webview_flutter/webview_flutter.dart';
// 加载本地文件为H5页面
// 需要先添加如下依赖
// flutter pub add path_provider

const String htmlStr = '''
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="utf-8" />
  <title>js通过channel向flutter传递数据</title>
</head>
<body>
  <h1>加载了本地文件为H5页面</h1>
  <button id="btn" style="font-size: 2.5em">传递参数</button>
</body>
</html>
''';

class FlutterH5JumpHtmlFile extends StatefulWidget {
  const FlutterH5JumpHtmlFile({super.key});

  @override
  State<FlutterH5JumpHtmlFile> createState() => _FlutterH5JumpHtmlFileState();
}

class _FlutterH5JumpHtmlFileState extends State<FlutterH5JumpHtmlFile> {
  late WebViewController controller;

  get _loadBtn => FilledButton(onPressed: (){
    _onLoadLocalFileH5(context);
  }, child: const Text('加载本地文件为H5页面',style: const TextStyle(color: Colors.white),));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('打开本地文件h5页面'), actions: [_loadBtn],),
      body: WebViewWidget(controller: controller),
    );
  }

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted);
  }

  void _onLoadLocalFileH5(BuildContext context) async {
    final String path = await _prepareFile();// 获取创建文件的绝对路径
    await controller.loadFile(path);
  }

  // 将字符串保存为H5页面文件到手机本地路径下
  _prepareFile() async {
    final tmpDir = (await getTemporaryDirectory()).path;
    final File file = File(<String>{tmpDir,'hi','index.html'}.join(Platform.pathSeparator));
    await file.create(recursive: true);
    await file.writeAsString(htmlStr);
    return file.path;
  }
}
